package cn.willbj.brief.hootl.lock.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 线程状态 thread dump示例 https://blog.csdn.net/helowken2/article/details/95060830
 *
 */
public class Demo04 {

	static int i = 0;

	public static void main(String[] args) {
		ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);

		/*new Thread(new Runnable() {
			@Override
			public void run() {
				Lock lock = readWriteLock.readLock();
				lock.lock();
				while (i<20){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("01: "+i++);
				}
				lock.unlock();
			}
		}).start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				Lock lock = readWriteLock.readLock();
				lock.lock();
				while (i<40){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("02: "+i);
				}
				lock.unlock();
			}
		}).start();*/

		// 写
		new Thread(new Runnable() {
			@Override
			public void run() {
				Lock lock = readWriteLock.writeLock();
				lock.lock();
				while (i<20){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("01: "+i++);
				}
				lock.unlock();
			}
		}).start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				Lock lock = readWriteLock.writeLock();
				lock.lock();
				while (i<40){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("02: "+i);
				}
				lock.unlock();
			}
		}).start();
	}
	

}
